<?php
/**
 * Login.php
 * Created by PhpStorm.
 * User: 江小波
 * Date: 2019/06/05
 * Time: 21:47
 */
namespace app\api\open\member;

use app\api\model\MemberModel;
use app\api\open\Base;
use app\common\utils\rsa\Rsa1024;
use think\Cache;
use think\Validate;

class Login extends Base
{
    protected $username = "";
    protected $password = "";

    /**
     * Login constructor.
     * @param array $param
     * @throws \Exception
     */
    public function __construct($param=[])
    {
        parent::__construct($param);

        $param = $this->params;

        $validate = new Validate([
            "username" => "require",
            "password" => "require|min:6"
        ],[
            "username.require" => "用户名必填",
            "password.require" => "密码必填",
            "password.min" => "密码至少6位以上"
        ]);

        if($validate->check($param) === false) {
            throw new \Exception($validate->getError(),1);
        }

        $this->username = $param['username'];
        $this->password = $param['password'];
    }

    protected function token($user=[],$type='single')
    {
        if(empty($user['id']))
        {
            return false;
        }
        $cache = Cache::store('redis');
        $redisHandler = $cache->handler();
        $uniqid = uniqid('member_');
        if($type === 'batch')
        {
            // 实现多点登录
            $redis_key = md5("member_token_".$user['id'].$uniqid);
            // 重置token=type|redis_key
            $token = "{$type}|{$redis_key}";
        }
        else
        {
            // 创建唯一登录标识实现单点登录
            $redis_key = md5("member_token_".$user['id']);
            $user['__uniqid__'] = $uniqid;
            // 重置token=type|redis_key|uniqid
            $token = "{$type}|{$redis_key}|{$uniqid}";
        }
        // 缓存5分钟
        @$redisHandler->setex($redis_key,5*60,json_encode($user));
        return Rsa1024::encryptByPub($token);
    }

    /**
     * @param array $param
     * @return array|mixed|object|string
     * @throws \Exception
     */
    public function signIn($param=[])
    {
        $info = MemberModel::getInstance()->get(['username'=>$this->username]);
        if(empty($info['id']))
        {
            throw new \Exception("该会员不存在",2);
        }
        if(empty($info['status']))
        {
            throw new \Exception("该会员被禁用",2);
        }

        if($info['password'] !== md5(md5($this->password)))
        {
            throw new \Exception("密码错误！",2);
        }

        // 成功登录
        return $this->token(['id'=>$info['id']],'single');
//        return $this->token(['id'=>$info['id']],'batch');
    }
}